package com.ruoyi.file.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Component
public class OssUtil {

    private final OSS ossClient;

    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.urlPrefix}")
    private String urlPrefix;

    public OssUtil(OSS ossClient) {
        this.ossClient = ossClient;
    }

    /**
     * 上传文件到 OSS，并返回可访问 URL
     */
    public String upload(MultipartFile file) throws IOException {
        // 按日期分层，例如 2025/07/14/uuid_filename.ext
        String datePath = LocalDate.now().toString().replace("-", "/");
        String objectName = datePath + "/"
                + UUID.randomUUID().toString().replace("-", "")
                + "_" + file.getOriginalFilename();

        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (OSSException | ClientException e) {
            throw new IOException("OSS 上传失败：" + e.getMessage(), e);
        }

        // 确保 urlPrefix 末尾只有一个 '/'
        String prefix = urlPrefix.endsWith("/") ? urlPrefix : urlPrefix + "/";
        return prefix + objectName;
    }

    /**
     * 删除 OSS 上的文件，参数为完整的访问 URL
     */
    public void delete(String fileUrl) throws IOException {
        if (!fileUrl.startsWith(urlPrefix)) {
            throw new IllegalArgumentException("非法的文件 URL：" + fileUrl);
        }
        // 从 URL 中提取出 objectName
        String objectName = fileUrl.substring(
                urlPrefix.endsWith("/") ? urlPrefix.length() : urlPrefix.length() + 1
        );
        try {
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException | ClientException e) {
            throw new IOException("OSS 删除失败：" + e.getMessage(), e);
        }
    }
}
